package com.sairobo.base.common.support;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.sairobo.base.common.constant.DataBaseFieldConstant;
import com.sairobo.base.common.utils.ShiroUtils;
import org.apache.ibatis.reflection.MetaObject;

/**
* @Description:自定义字段填充器
* @updateTime shengming 2017/11/7 13:59
*/
public class MyMetaObjectHandler extends MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        // 创建用户
        Object createBy = getFieldValByName(DataBaseFieldConstant.CREATE_BY, metaObject);
        if (createBy == null) {
            setFieldValByName(DataBaseFieldConstant.CREATE_BY, ShiroUtils.getSubject().getPrincipal(), metaObject);
        }

        // 删除标记
        Object delFlag = getFieldValByName(DataBaseFieldConstant.DEL_FLAG, metaObject);
        if (delFlag == null) {
            setFieldValByName(DataBaseFieldConstant.DEL_FLAG, DataBaseFieldConstant.DEL_FLAG_NORMAL, metaObject);
        }

        // 乐观锁
        Object version = getFieldValByName(DataBaseFieldConstant.VERSION, metaObject);
        if (version == null) {
            setFieldValByName(DataBaseFieldConstant.VERSION, 0, metaObject);
        }
    }

    /**
     * 只有 openUpdateFill() = true,才启用updateFill(X)方法
     * 原理 见源码：com.baomidou.mybatisplus.MybatisDefaultParameterHandler 74行
     * @return
     */
    @Override
    public boolean openUpdateFill() {
        return true;
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新用户
//        Object updateBy = getFieldValByName(DataBaseFieldConstant.UPDATE_BY, metaObject);
//        if (updateBy == null) {
//            setFieldValByName(DataBaseFieldConstant.UPDATE_BY, ShiroUtils.getSubject().getPrincipal(), metaObject);
//        }
//
//        // 删除时间
//        Object deleteTime = getFieldValByName(DataBaseFieldConstant.DEL_TIME, metaObject);
//        Object delFlag = getFieldValByName(DataBaseFieldConstant.DEL_FLAG, metaObject);
//        if (Integer.parseInt((String)delFlag)==1) {
//            setFieldValByName(DataBaseFieldConstant.UPDATE_TIME, new Date(), metaObject);
//        }
    }


}
